# coding=utf-8
"""
*   Coder : Dzlua
*   Email : 505544956@qq.com
*   Time  : 2017/09/23
"""
#--------------------------#
import config
from flask import Flask, jsonify, request
from flask_script import Manager, Command
from flask_sqlalchemy import SQLAlchemy

#--------------------------#
app = Flask(__name__)
#
app.config['SECRET_KEY'] = config.SECRET_KEY
app.config['SQLALCHEMY_DATABASE_URI'] = config.SQLALCHEMY_DATABASE_URI
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = config.SQLALCHEMY_COMMIT_ON_TEARDOWN
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = config.SQLALCHEMY_TRACK_MODIFICATIONS
#
manager = Manager(app)
db = SQLAlchemy(app)

#--------------------------#
class MgrInstall(Command):
    '''install scripts.'''
    def run(self):
        print('install...')
        db.create_all()
        print('install done!')
#
manager.add_command('install', MgrInstall)

#--------------------------#
class DBUser(db.Model):
    __tablename__ = 'scripts'
    id = db.Column(db.Integer, primary_key = True)
    username = db.Column(db.String(32), index = True)
    password_hash = db.Column(db.String(128))
#
#--------------------------#
@app.route('/')
def index():
    data = {
        'hello': 'world'
    }
    return jsonify(data)
#----------#
@app.route('/users/')
def RTUsers():
    users = DBUser.query.filter('id<=:num').params({'num': 3}).all()
    #
    data = {
        'count': len(users),
        'users': [],
    }
    #
    for user in users:
        info = {'id': user.id, 'username': user.username}
        data['users'].append(info)
    #
    return jsonify(data)
#----------#
@app.route('/adduser/')
def RTAddUser():
    args = request.args or request.form
    username = args.get('username')
    password = args.get('password')
    #
    if not username or not password:
        return jsonify('no username or password')
    #
    if DBUser.query.filter_by(username=username).first() is not None:
        return jsonify('%s already exist' % username)
    #
    user = DBUser(username=username,password_hash=password)
    db.session.add(user)
    db.session.commit()
    #
    return jsonify('ok')
    
#--------------------------#
if __name__ == '__main__':
    manager.run()
#--------------------------#
